﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using CapstoneProjectAEReader.Business.E_book_Reader;
using CapstoneProjectAEReader.Common.Exceptions;
using CapstoneProjectAEReader.Entities.Models;
using CapstoneProjectAEReader.DataAccess.DBAccess;
using CapstoneProjectAEReader.Business.Others;
using CapstoneProjectAEReader.Common.Utility;
using CapstoneProjectAEReader.GUIs.TranslationGUI;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using TreeView = System.Windows.Controls.TreeView;
using CapstoneProjectAEReader.DataAccess.DBAccess;
using CapstoneProjectAEReader.Entities.Models;
using CapstoneProjectAEReader.GUIs.Others;
using System.Threading.Tasks;
using ListViewItem = System.Windows.Forms.ListViewItem;
using System.Windows.Threading;
using System.IO;
using System.Windows.Input;
using System.ComponentModel;
using Clipboard = System.Windows.Clipboard;
using ContextMenu = System.Windows.Controls.ContextMenu;
using IDataObject = System.Windows.IDataObject;
using MenuItem = System.Windows.Controls.MenuItem;
using TextDataFormat = System.Windows.TextDataFormat;

namespace CapstoneProjectAEReader.GUIs.ReaderGUI
{
    /// <summary>
    /// Interaction logic for ReaderGui.xaml
    /// </summary>
    public partial class ReaderGui : Window
    {
        #region Attributes

        private string _fileName;
        private Business.E_book_Reader.IBook _readerControl;
        public XmlDocument xDoc;
        public TreeViewItem TreeViewItemParent;
        public TreeViewItem TreeViewItemSelected;
        public bool BlParentIsTreeView = true;
        public bool BlIsTreeView = true;
        public int intCurrentPageNumber = 1;
        public string strSelectedTextGlobal;

        private RoutedPropertyChangedEventArgs<object> _objE;
        private DAO _dao;
        private Ebook _ebook;
        private string _checkFileType = null;
        private Type _baseType;
        private Dictionary<string, string> _dllDic = new Dictionary<string, string>();

        private const string EbookNotExist = "ebookNotExist";
        private const string EbookExisted = "ebookExisted";
        private const string FirstPage = "firstPage";
        private const string LastPage = "lastPage";
        private const string PreviousPage = "previousPage";
        private const string NextPage = "nextPage";
        private const string ZoomIn = "zoomIn";
        private const string ZoomOut = "zoomOut";
        private const string Search = "search";
        private const string Note = "note";
        private const string Translate = "translate";
        private const string AddToLib = "addToLib";
        private const string InvalidPageNo = "invalidPageNo";
        private const string DeleteBookmarkConfirmation = "deleteBookmarkConfirmation";
        private const string DeleteNoteDetailConfirmation = "deleteNoteDetailConfirmation";
        private const string EbookNotSupported = "ebookNotSupported";
        private const string Addbookmark = "addBookmark";
        private const string EditBookmark = "updateBookmark";
        private const string DeleteBookmark = "deleteBookmark";
        private const string SelectNoteWarn = "selectNoteWarn";
        private const string DeleteNote = "deleteNote";
        private const string UpdateNote = "editNote";
        private const string GoToNote = "gotoNote";
        private const string GoToPage = "gotoPage";

        private string fileExtension = "";
        private object readerObj = null;
        private Business.E_book_Reader.IBook readerObjectPrototype;
        private string LoadingPoint = "";
        private string progress = "Loading";
        private BitmapImage _bi3;

        #endregion

        public ReaderGui(string fileName, DTO dto)
        {
            InitializeComponent();
            try
            {
                _fileName = fileName;
                _dao = new DAO(dto);
                fileExtension = System.IO.Path.GetExtension(fileName);

                //---Load controller---
                
                _dllDic =
                    Utilities.LoadXml(Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                      Constants.StorageStructure.MappingXmlFile);
                if (_dllDic.ContainsKey(fileExtension))
                {
                    string dllPath = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                     _dllDic[fileExtension];
                    Type[] dllTypes = Assembly.LoadFrom(dllPath).GetTypes();
                    string ebookType = fileExtension.Split(Constants.CommonCharacters.Dot)[1];
                    foreach (var dllType in dllTypes)
                    {
                        if (dllType.Name.Contains(ebookType))
                        {
                            readerObj = Utilities.GetReadingController(dllType, new object[] { fileName });
                            _baseType = dllType;
                        }
                    }
                }
                else
                {
                    throw new AeException(Constants.ExceptionCode.Function,
                                          ResourceReader.GetResourceContent(EbookNotSupported));
                }
                readerObjectPrototype = (Business.E_book_Reader.IBook)readerObj;

                //var temp = (Business.E_book_Reader.IBook)readerObj;
                //_ebook = temp.GenerateEbookObj(fileName);
                //_checkFileType = _ebook.Type;
                //_dao = new DAO(dto);

                //this.ebookControl.MouseWheel += OnMouseWheel;
                //this.ebookControl.MouseDown += OnMouseDown;

                if (Constants.EbookType.Pdf.Equals(fileExtension))
                {
                    _bi3 = new BitmapImage();
                    _bi3.BeginInit();
                    _bi3.UriSource = new Uri(@"Images/LoadingPDF.png", UriKind.RelativeOrAbsolute);
                    _bi3.EndInit();
                    LoadingImage.Source = _bi3;
                }
                else if (Constants.EbookType.Epub.Equals(fileExtension))
                {
                    _bi3 = new BitmapImage();
                    _bi3.BeginInit();
                    _bi3.UriSource = new Uri(@"Images/LoadingEpub.png", UriKind.RelativeOrAbsolute);
                    _bi3.EndInit();
                    LoadingImage.Source = _bi3;
                }
                //----------Loading Part----------
                rotate.Angle = 0;
                group.Children.Add(rotate);
                LoadingImage.RenderTransform = group;
                startDispatcher();
                //-----------------------------
                startLoadingMetaData();
            }
            catch (AeException aex)
            {
                throw aex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public ReaderGui(Ebook ebook, DTO dto)
        {
            InitializeComponent();
            _ebook = ebook;
            _dao = new DAO(dto);
            InitReaderControl(_fileName);
            ebookControl.Child = _readerControl;
            ReloadFormLanguage();
            RebindData();
            AddToRecentRead(_ebook);
        }

        #region Load MetaData

        private void startLoadingMetaData()
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteLoadingMetaData);
            worker.DoWork += new DoWorkEventHandler(LoadMetaData);
            worker.RunWorkerAsync();
        }

        private void CompleteLoadingMetaData(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker finishWorker = sender as BackgroundWorker;
            finishWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(CompleteLoadingMetaData);
            finishWorker.DoWork -= new DoWorkEventHandler(LoadMetaData);
            ReloadFormLanguage();
            RebindData();
            AddToRecentRead(_ebook);
            InitReaderControl(_fileName);
            ebookControl.Child = _readerControl;
            //MessageBox.Show("Done");
        }

        private void LoadMetaData(object sender, DoWorkEventArgs e)
        {
            progress = "Loading Book";
            if (readerObjectPrototype != null && _fileName != null)
            {
                _ebook = readerObjectPrototype.GenerateEbookObj(_fileName);
            }
            //_ebook = EbookObjectGenerator.GenerateEbookObj(_fileName);
            _checkFileType = _ebook.Type;
            if (_dao.CheckEbookExist(_ebook))
            {
                _ebook = _dao.SelectEbook(_ebook.Title, _ebook.Author);
            }
        }

        #endregion

        private void InitReaderControl(string fileName)
        {
            object readerControl = Utilities.GetReadingController(_baseType, new object[] { fileName });
            _readerControl = (Business.E_book_Reader.IBook)readerControl;
            lbTotalPageNo.Text = _ebook.PageCount.ToString();
        }

        #region EPUB

        private DispatcherTimer ReaderDispatcher = new System.Windows.Threading.DispatcherTimer();
        private int TimeCount = 0;
        private RotateTransform rotate = new RotateTransform();
        private TransformGroup group = new TransformGroup();


        public void startDispatcher()
        {
            ReaderDispatcher.Tick += new EventHandler(LoadPage);
            ReaderDispatcher.Interval = new TimeSpan(0, 0, 0, 0, 1);
            ReaderDispatcher.Start();
        }

        private void LoadPage(object sender, EventArgs e)
        {
            /*if (_readerControl != null)
            {
                System.Diagnostics.Debug.WriteLine(_readerControl.CheckLoading());
            }*/
            if (_readerControl != null && _readerControl.CheckLoading() == "Done")
            {
                ebookControl.Visibility = Visibility.Visible;
                LoadingField.Visibility = Visibility.Hidden;
                ReaderDispatcher.Tick -= new EventHandler(LoadPage);
                ReaderDispatcher.Interval = new TimeSpan(0, 0, 1);
                if (Constants.EbookType.Pdf.Equals(_checkFileType))
                {
                    ReaderDispatcher.Stop();
                    ReaderDispatcher = null;
                }
                else
                {
                    ReaderDispatcher.Tick += new EventHandler(CheckPage);
                }
            }
            else
            {
                TimeCount += 1;
                if (TimeCount / 75 == 1)
                {
                    LoadingPoint = " .";
                }
                else if (TimeCount / 75 == 2)
                {
                    LoadingPoint = " . .";
                }
                else if (TimeCount / 75 == 3)
                {
                    LoadingPoint = " . . .";
                    TimeCount = 0;
                }
                LoadingLabel.Content = progress + LoadingPoint;
                rotate.Angle += 1;
                LoadingImage.RenderTransform = group;
            }
            
        }

        private void CheckPage(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Check Page!");
            CurrentPage.Content = _readerControl.CheckCurrentPage();
            CommandManager.InvalidateRequerySuggested();
        }

        #endregion

        #region PDF

        public Grid GetReaderTab()
        {
            return BookReadingGrid;
        }

        public void ReloadFormLanguage()
        {
            lbFirstPage.Content = ResourceReader.GetResourceContent(FirstPage);
            lbAddToLib.Content = ResourceReader.GetResourceContent(AddToLib);
            if (_dao.CheckEbookExist(_ebook))
            {
                AddToLibImage.Source = new BitmapImage(new
                                                           Uri(@"pack://application:,,,/GUIs/ReaderGUI/Images/addDB.png"));
            }
            else
            {
                AddToLibImage.Source = new BitmapImage(new
                                                           Uri(
                                                           @"pack://application:,,,/GUIs/ReaderGUI/Images/addDBOff.png"));
            }
            lbLastPage.Content = ResourceReader.GetResourceContent(LastPage);
            lbNextPage.Content = ResourceReader.GetResourceContent(NextPage);
            lbNote.Content = ResourceReader.GetResourceContent(Note);
            lbPrevPage.Content = ResourceReader.GetResourceContent(PreviousPage);
            lbSearch.Content = ResourceReader.GetResourceContent(Search);
            lbTranslate.Content = ResourceReader.GetResourceContent(Translate);
            //lbTotalPageNo.Text = _ebook.PageCount.ToString();
            lbZoomIn.Content = ResourceReader.GetResourceContent(ZoomIn);
            lbZoomOut.Content = ResourceReader.GetResourceContent(ZoomOut);
            var bmCtMenu = (ContextMenu)Resources["bookmarkTabContextMenu"];
            MenuItem tempMenuItem = (MenuItem)bmCtMenu.Items[0];
            tempMenuItem.Header = ResourceReader.GetResourceContent(Addbookmark);
            tempMenuItem = (MenuItem)bmCtMenu.Items[1];
            tempMenuItem.Header = ResourceReader.GetResourceContent(EditBookmark);
            tempMenuItem = (MenuItem)bmCtMenu.Items[2];
            tempMenuItem.Header = ResourceReader.GetResourceContent(DeleteBookmark);
            var noteCtMenu = (ContextMenu)Resources["noteTabContextMenu"];
            tempMenuItem = (MenuItem)noteCtMenu.Items[0];
            tempMenuItem.Header = ResourceReader.GetResourceContent(GoToNote);
            tempMenuItem = (MenuItem)noteCtMenu.Items[1];
            tempMenuItem.Header = ResourceReader.GetResourceContent(UpdateNote);
            tempMenuItem = (MenuItem)noteCtMenu.Items[2];
            tempMenuItem.Header = ResourceReader.GetResourceContent(DeleteNote);
            btAddBookmark.ToolTip = ResourceReader.GetResourceContent(Addbookmark);
            btEditBookmark.ToolTip = ResourceReader.GetResourceContent(EditBookmark);
            btDelBookmark.ToolTip = ResourceReader.GetResourceContent(DeleteBookmark);
            btEditNote.ToolTip = ResourceReader.GetResourceContent(UpdateNote);
            btDelNote.ToolTip = ResourceReader.GetResourceContent(DeleteNote);
            btGotoPage.ToolTip = ResourceReader.GetResourceContent(GoToPage);
        }

        public void RebindData()
        {
            NoteWordListView.ItemsSource = null;
            NoteWordListView.ItemsSource = _dao.GetNoteOfEbook(_ebook.Id);
        }

        private void HandleBtNote(object sender, RoutedEventArgs e)
        {
            string text = strSelectedTextGlobal;
            if (Constants.EbookType.Epub.Equals(_checkFileType))
            {
                text = _readerControl.GetSelectedText();
            }
            if (string.IsNullOrEmpty(text))
            {
                text = "";
            }



            if (_dao.CheckEbookExist(_ebook))
            {
                
                if (_dao.CheckNoteExist(text))
                {
                    Note tempNote = _dao.GetNote(text);
                    if (_dao.CheckNoteDetailExist(tempNote.NoteId, _ebook.Id))
                    {
                        NoteDetail tempNoteDetail = new NoteDetail();
                        tempNoteDetail.Bookid = _ebook.Id;
                        tempNoteDetail.PageNumber = intCurrentPageNumber;
                        tempNoteDetail.Createdate = DateTime.Now.ToString(Constants.FullDateTimeFormatToSecond);
                        Exist temp = new Exist(tempNote, _dao.Dto, tempNoteDetail, this);
                        temp.ShowDialog();
                    }
                    else
                    {
                        Blank temp = new Blank(text, _ebook.Id, _dao.Dto, intCurrentPageNumber, this);
                        temp.ShowDialog();
                    }
                }
                else
                {
                    Blank temp = new Blank(text, _ebook.Id, _dao.Dto, intCurrentPageNumber, this);
                    temp.ShowDialog();
                }
            }
            else
            {
                Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(EbookNotExist));
            }
            //Clipboard.Clear();
            strSelectedTextGlobal = text;
        }

        private void labelExpand_Collapsed(object sender, RoutedEventArgs e)
        {
            noteTab.Visibility = Visibility.Collapsed;
            bookMarkTab.Visibility = Visibility.Collapsed;
        }

        private void labelExpand_Expanded(object sender, RoutedEventArgs e)
        {
            noteTab.Visibility = Visibility.Collapsed;
            bookMarkTab.Visibility = Visibility.Collapsed;

            if (labelExpand.Content.Equals("Bookmark"))
            {
                bookMarkTab.Visibility = Visibility.Visible;
                labelExpand.IsExpanded = true;
            }
            else if (labelExpand.Content.Equals("Note"))
            {
                noteTab.Visibility = Visibility.Visible;
                labelExpand.IsExpanded = true;
            }
            else
            {
                labelExpand.IsExpanded = false;
            }
        }

        private void AddToRecentRead(Ebook ebook)
        {
            if (!_dao.Dto.SettingDetail.RecentRead.Any(e => e.Title == ebook.Title && e.Author == ebook.Author))
            {
                if (_dao.Dto.SettingDetail.RecentRead.Count == 7)
                {
                    _dao.Dto.SettingDetail.RecentRead.RemoveAt(0);
                }
                _dao.Dto.SettingDetail.RecentRead.Add(ebook);
            }
        }

        private void BookMark_Click(object sender, RoutedEventArgs e)
        {
            noteTab.Visibility = Visibility.Collapsed;
            bookMarkTab.Visibility = Visibility.Visible;
            labelExpand.Content = "Bookmark";
            labelExpand.IsExpanded = true;
            BookmarkItemsList.Items.Clear();
            _readerControl.LoadBookmark(BookmarkItemsList, _ebook.BookmarkPath);
            TreeViewItem item = (TreeViewItem)BookmarkItemsList.Items[0];

            if (item != null)
            {
                item.IsSelected = true;
            }
        }

        private void Note_Click(object sender, RoutedEventArgs e)
        {
            noteTab.Visibility = Visibility.Visible;
            bookMarkTab.Visibility = Visibility.Collapsed;
            labelExpand.Content = "Note";
            labelExpand.IsExpanded = true;
        }

        private void btNextPage_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.DisplayNextPage();
            if (intCurrentPageNumber < _ebook.PageCount)
            {
                intCurrentPageNumber++;
                CurrentPage.Content = intCurrentPageNumber.ToString();
            }
        }

        private void btPreviousPage_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.DisplayPrevioudPage();
            if (intCurrentPageNumber > 0)
            {
                intCurrentPageNumber--;
                CurrentPage.Content = intCurrentPageNumber.ToString();
            }
        }

        private void btLastPage_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.DisplayLastPage();
            intCurrentPageNumber = _ebook.PageCount;
            CurrentPage.Content = intCurrentPageNumber.ToString();
        }

        private void btFirstPage_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.DisplayFirstPage();
            intCurrentPageNumber = 1;
            CurrentPage.Content = intCurrentPageNumber.ToString();
        }

        private void btZoomIn_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.ZoomIn();
        }

        private void btZoomOut_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.ZoomOut();
        }

        private void btNote_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            else
            {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
        }


        private void btSearch_Click(object sender, RoutedEventArgs e)
        {
            _readerControl.SearchContent(_readerControl.GetSelectedText());
        }

        private void btSearch_MouseEnter(object sender, MouseEventArgs e)
        {
            //_readerControl.PressKeys();
            //ebookControl.Focus();
            //_readerControl.SearchContent(_readerControl.GetSelectedText());
        }

        private void btTranslate_Click(object sender, RoutedEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            if (Constants.EbookType.Epub.Equals(_checkFileType))
            {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            if (string.IsNullOrEmpty(strSelectedTextGlobal))
            {
                strSelectedTextGlobal = "";
            }

            string strSelectedText;
            strSelectedText = strSelectedTextGlobal;

            /*            Translation translationGui = new Translation(strSelectedText);
                        translationGui.Show();*/

            Thread thread = new Thread(() =>
                                           {
                                               Translation w = new Translation(strSelectedText, _dao.Dto, _ebook,
                                                                               intCurrentPageNumber);
                                               w.Show();
                                               w.Closed += (sender1, e1) => w.Dispatcher.InvokeShutdown();
                                               System.Windows.Threading.Dispatcher.Run();
                                           });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
            //System.Windows.Clipboard.Clear();
            strSelectedTextGlobal = strSelectedText;
        }

        private void btAddToLib_Click(object sender, RoutedEventArgs e)
        {
            if (_dao.CheckEbookExist(_ebook))
            {
                Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(EbookExisted));
            }
            else
            {
                string strXmlOldPath;
                strXmlOldPath = _ebook.BookmarkPath;
                _ebook.Path = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                              Constants.StorageStructure.EbookFolder + Constants.CommonCharacters.SlashString +
                              System.IO.Path.GetFileName(_ebook.Path);
                _ebook.BookmarkPath = Utilities.GetCurrentLocation() + Constants.CommonCharacters.SlashString +
                                      Constants.StorageStructure.EbookFolder + Constants.CommonCharacters.SlashString +
                                      _ebook.Title + Constants.XmlExtension;
                _ebook.Group.Add(Constants.UnGroup);
                _ebook.GroupInText = Utilities.ReturnGroupInText(_ebook.Group);
                _ebook.Id = _dao.InsertEbook(_ebook);

                Utilities.CopyFile(_fileName, _ebook.Path);
                Utilities.CopyFile(strXmlOldPath, _ebook.BookmarkPath);
                AddToLibImage.Source = new BitmapImage(new
                                                           Uri(@"pack://application:,,,/GUIs/ReaderGUI/Images/addDB.png"));
            }
            noteTab.Visibility = Visibility.Collapsed;
            bookMarkTab.Visibility = Visibility.Collapsed;
        }

        private void btAddBookmark_Click(object sender, RoutedEventArgs e)
        {
            string strHeaderText = strSelectedTextGlobal;
            if (Constants.EbookType.Epub.Equals(_checkFileType))
            {
                strHeaderText = _readerControl.GetSelectedText();
            }
            if (string.IsNullOrEmpty(strHeaderText))
            {
                strHeaderText = "";
            }

            string strSelectedItem;
            string strTotalpage;
            strSelectedItem = BookmarkItemsList.SelectedValue.ToString();
            //MessageBox.Show(strSelectedItem);
            strSelectedItem = strSelectedItem.Substring(strSelectedItem.IndexOf("Header") + 7,
                                                        strSelectedItem.IndexOf("Items") -
                                                        strSelectedItem.IndexOf("Header") - 7);

            strTotalpage = lbTotalPageNo.Text;
            bool isUpdate = false;
            BookmarkHeader bookmarkHeader = new BookmarkHeader(strTotalpage, isUpdate);
            
            //this.AddChild(bookmarkHeader);
            if (strHeaderText.Length > 0)
            {
                int getPage = 0;
                try
                {
                    getPage = Int16.Parse(CurrentPage.Content.ToString());
                }
                catch (Exception)
                {
                }
                bookmarkHeader = new BookmarkHeader(strTotalpage, isUpdate, strHeaderText, getPage);
            }
            else
            {
                bookmarkHeader = new BookmarkHeader(strTotalpage, isUpdate);
            }
            if (bookmarkHeader.ShowDialog() == true)
            {
                string strHeader = bookmarkHeader.StrHeader;
                string strPageNumber = bookmarkHeader.StrPageNumber;
                var subitem = new TreeViewItem() { Header = strHeader };
                if (BlIsTreeView)
                {
                    //do nothing
                }
                else
                {
                    if (BlParentIsTreeView)
                    {
                        //parent item is root node
                        BookmarkItemsList.Items.Add(subitem);
                        _readerControl.AddBookmark(_objE, strSelectedItem, strHeader, strPageNumber);
                        //_readerControl.DeleteBookmark(objE, strSelectedItem);
                    }
                    else
                    {
                        TreeViewItemParent.Items.Add(subitem);
                        _readerControl.AddBookmark(_objE, strSelectedItem, strHeader, strPageNumber);
                        //_readerControl.DeleteBookmark(objE, strSelectedItem);
                    }
                }
            }
            //System.Windows.Clipboard.Clear();
            strSelectedTextGlobal = strHeaderText;
        }

        private void btDelBookmark_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBoxResult.OK ==
                Utilities.ShowConfirmationMesBox(ResourceReader.GetResourceContent(DeleteBookmarkConfirmation)))
            {
                string strSelectedItem;
                strSelectedItem = BookmarkItemsList.SelectedValue.ToString();
                //MessageBox.Show(strSelectedItem);
                strSelectedItem = strSelectedItem.Substring(strSelectedItem.IndexOf("Header") + 7,
                                                            strSelectedItem.IndexOf("Items") -
                                                            strSelectedItem.IndexOf("Header") - 7);
                if (BlIsTreeView)
                {
                    //do nothing
                }
                else
                {
                    if (BlParentIsTreeView)
                    {
                        //parent item is root node
                        BookmarkItemsList.Items.Remove(TreeViewItemSelected);
                        _readerControl.DeleteBookmark(_objE, strSelectedItem);
                    }
                    else
                    {
                        TreeViewItemParent.Items.Remove(TreeViewItemSelected);
                        _readerControl.DeleteBookmark(_objE, strSelectedItem);
                    }
                }
            }
        }

        private void BookmarkItemsList_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            string strSelectedItem;
            string strBookmarkPageNumber;
            int intBookmarkPageNumber;
            strSelectedItem = BookmarkItemsList.SelectedValue.ToString();
            //MessageBox.Show(strSelectedItem);
            strSelectedItem = strSelectedItem.Substring(strSelectedItem.IndexOf("Header") + 7,
                                                        strSelectedItem.IndexOf("Items") -
                                                        strSelectedItem.IndexOf("Header") - 7);
            try
            {
                strBookmarkPageNumber = _readerControl.GetBookmarkPageNumber(e, strSelectedItem);
                _objE = e;
                if (strBookmarkPageNumber.Length != 0)
                {
                    intBookmarkPageNumber = int.Parse(strBookmarkPageNumber);
                    _readerControl.GoToPage(intBookmarkPageNumber);
                }
                try
                {
                    if (
                        BookmarkItemsList.ItemContainerGenerator.ContainerFromIndex(0).Equals(
                            (TreeViewItem)((TreeView)sender).SelectedItem))
                    {
                        //selected node is root node
                        BlIsTreeView = true;
                    }
                    else
                    {
                        BlIsTreeView = false;
                        TreeViewItemSelected = (TreeViewItem)((TreeViewItem)((TreeView)sender).SelectedItem);
                        if (((TreeViewItem)((TreeView)sender).SelectedItem).Parent is TreeView)
                        {
                            BlParentIsTreeView = true;
                        }
                        else
                        {
                            if (sender is TreeView && ((TreeViewItem)((TreeView)sender).SelectedItem).Parent != null)
                            {
                                TreeViewItemParent = (TreeViewItem)((TreeViewItem)((TreeView)sender).SelectedItem).Parent;
                                BlParentIsTreeView = false;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
            catch (Exception)
            {
            }
        }

        private void btEditBookmark_Click(object sender, RoutedEventArgs e)
        {
            string strSelectedItem;
            string strTotalpage;
            strSelectedItem = BookmarkItemsList.SelectedValue.ToString();
            //MessageBox.Show(strSelectedItem);
            strSelectedItem = strSelectedItem.Substring(strSelectedItem.IndexOf("Header") + 7,
                                                        strSelectedItem.IndexOf("Items") -
                                                        strSelectedItem.IndexOf("Header") - 7);

            strTotalpage = lbTotalPageNo.Text;
            bool isUpdate = true;
            BookmarkHeader bookmarkHeader = new BookmarkHeader(strTotalpage, isUpdate, strSelectedItem);

            //this.AddChild(bookmarkHeader);

            if (bookmarkHeader.ShowDialog() == true)
            {
                string strHeader = bookmarkHeader.StrHeader;
                var subitem = new TreeViewItem() { Header = strHeader };
                if (BlIsTreeView)
                {
                    //do nothing
                }
                else
                {
                    TreeViewItemSelected.Header = strHeader;
                    _readerControl.UpdateBookmark(_objE, strSelectedItem, strHeader);
                }
            }

        }

        private void btTranslate_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            else {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
        }

        private void HandleDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (NoteWordListView.SelectedItems.Count == 1)
            {
                Note selectedItem = (Note)NoteWordListView.SelectedItem;
                Blank tmlForm = new Blank(selectedItem, _ebook.Id, _dao.Dto, this);
                tmlForm.Show();
            }
        }

        private void HandleBtDelNote(object sender, RoutedEventArgs e)
        {
            if (MessageBoxResult.OK ==
                Utilities.ShowConfirmationMesBox(ResourceReader.GetResourceContent(DeleteNoteDetailConfirmation)))
            {
                if (NoteWordListView.SelectedItems.Count > 0)
                {
                    Note selectedItem = (Note)NoteWordListView.SelectedItem;
                    NoteDetail selectedNoteDetail = _dao.GetNoteDetail(selectedItem.NoteId, _ebook.Id);
                    _dao.DeleteNoteDetail(selectedNoteDetail);
                    RebindData();
                }
                else
                {
                    Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(SelectNoteWarn));
                }
            }
        }

        private void btGotoPage_Click(object sender, RoutedEventArgs e)
        {
            int intPageNumber;
            try
            {
                intPageNumber = int.Parse(txtPageNo.Text);
                if (intPageNumber < 0 || intPageNumber > int.Parse(lbTotalPageNo.Text))
                {
                    Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(InvalidPageNo));
                }
                else
                {
                    _readerControl.GoToPage(intPageNumber);
                }
            }
            catch (Exception)
            {
                Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(InvalidPageNo));
            }
        }

        private void btAddBookmark_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            else
            {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
        }

        private void ebookControl_MouseLeave(object sender, MouseEventArgs e)
        {
            //_readerControl.PressKeys();
        }

        private void toolBar1_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                if (_readerControl != null)
                {
                    _readerControl.PressKeys();
                    strSelectedTextGlobal = _readerControl.GetSelectedText();
                }
                else
                {
                    strSelectedTextGlobal = _readerControl.GetSelectedText();
                }
            }
        }

        private void statusbar_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            else
            {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
        }

        private void panel_MouseEnter(object sender, MouseEventArgs e)
        {
            if (Constants.EbookType.Pdf.Equals(_checkFileType))
            {
                _readerControl.PressKeys();
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
            else
            {
                strSelectedTextGlobal = _readerControl.GetSelectedText();
            }
        }

        private void HandleBtEditNote(object sender, RoutedEventArgs e)
        {
            if (NoteWordListView.SelectedItems.Count == 1)
            {
                Note selectedItem = (Note)NoteWordListView.SelectedItem;
                Blank tmlForm = new Blank(selectedItem, _ebook.Id, _dao.Dto, this);
                tmlForm.Show();
            }
            else
            {
                if (NoteWordListView.SelectedItems == null)
                {
                    Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(SelectNoteWarn));
                }
            }
        }

        private void HandleBtGoto(object sender, RoutedEventArgs e)
        {
            if (NoteWordListView.SelectedItems.Count == 1)
            {
                Note selectedItem = (Note)NoteWordListView.SelectedItem;
                NoteDetail selectedNoteDetail = _dao.GetNoteDetail(selectedItem.NoteId, _ebook.Id);
                _readerControl.GoToPage(selectedNoteDetail.PageNumber);
            }
            else
            {
                if (NoteWordListView.SelectedItems == null)
                {
                    Utilities.ShowWarningMesbox(ResourceReader.GetResourceContent(SelectNoteWarn));
                }
            }
        }

        #endregion

        private void Window_Closed(object sender, EventArgs e)
        {
            if (ReaderDispatcher != null)
            {
                ReaderDispatcher.Stop();
                ReaderDispatcher = null;
            }
            //MessageBox.Show("Closed");
        }
    }
}